package com.wswy.wzcx.widget.home;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.annotation.CheckResult;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.AppCompatImageView;
import android.text.Editable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SizeUtils;
import com.facebook.common.util.UriUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.wswy.wzcx.R;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.ui.other.DialogFactory;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.other.ViewHelp;

import com.wswy.wzcx.utils.FrescoUtils;
import com.wswy.wzcx.widget.home.TipMap.ContentType;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by wangduheng26 on 2018/3/5.
 * wangduheng26@gmail.com
 */

public class TipLayoutView extends RelativeLayout {
    private TipMap mTipMap;
    private TextView editText;
    Calendar chooseCalendar;
    private BindCallBack mBindCall;
    private ResultFilter filter;

    private SimpleDraweeView imgPhoto;
    private OnClickListener onClickListener;
    private String imgPath;

    public TipLayoutView(Context context, TipMap tipMap) {
        this(context, tipMap, null,null);
    }

    public TipLayoutView(Context context, TipMap tipMap, BindCallBack bindCall) {
        this(context, tipMap, bindCall, null);
    }

    public TipLayoutView(Context context, TipMap tipMap, BindCallBack bindCall, ResultFilter f) {
        super(context);
        mTipMap = tipMap;
        mBindCall = bindCall;
        filter = f;
        init(context);
    }

    public interface BindCallBack {
        void onBindView(TextView text);
    }

    public interface ResultFilter {
        boolean filter(@Nullable CharSequence editable);
    }


    private void init(Context context) {
        if (mTipMap == null) return;
        int type = mTipMap.type;
        int showHelp = mTipMap.showHelp;
        String topTip = mTipMap.topTip;



        setBackgroundColor(Color.WHITE);

        TextView tvTop = new TextView(context);
        tvTop.setId(ViewHelp.generateViewId());

        LayoutParams layoutParams = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);


        int dp = AndroidUtilities.dp(15);
        if(type != ContentType.TYPE_LABEL){
            setMinimumHeight(dip2Px(80));
            layoutParams.setMargins(0, 15, 0, 0);


            setPadding(dp, dp, dp, AndroidUtilities.dp(8));

            tvTop.setTextColor(ContextCompat.getColor(context,R.color.textColorTertiary));
            tvTop.setTextSize(13);

            editText = new EditText(context);

        }else {
            tvTop.setTextColor(ContextCompat.getColor(context,R.color.textColorSecondary));
            tvTop.setTextSize(14);

            LayoutHelper.setMargin(layoutParams,15,10,0,0);


            editText = new TextView(context);
        }


        addView(tvTop, layoutParams);


        editText.setId(ViewHelp.generateViewId());
        editText.setBackgroundColor(Color.TRANSPARENT);
        editText.setIncludeFontPadding(false);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        editText.setGravity(Gravity.BOTTOM);
        editText.setTextColor(ContextCompat.getColor(context, R.color.gray20));
        editText.setHintTextColor(ContextCompat.getColor(context, R.color.hint_color));
        editText.setGravity(Gravity.CENTER_VERTICAL);

        if (mBindCall != null) {
            mBindCall.onBindView(editText);
        }

        LayoutParams params = LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, tvTop.getId());
        boolean showArrow12 = false;
        if (type == TipMap.ContentType.TYPE_DATE) {
            editText.setFocusable(false);
            editText.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showChooseDate();
                }
            });
            params.addRule(RelativeLayout.ALIGN_LEFT, tvTop.getId());
            showArrow12 = true;

        } else if (type == TipMap.ContentType.TYPE_ADDRESS) {
            editText.setFocusable(false);
            editText.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAddressDialog();
                }
            });
            params.addRule(RelativeLayout.ALIGN_LEFT, tvTop.getId());
            showArrow12 = true;
        } else if (type == TipMap.ContentType.TYPE_CURRENCY) {
            TextView textView = new TextView(context);
            textView.setId(ViewHelp.generateViewId());
            textView.setText(R.string.money);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
            textView.setTextColor(ContextCompat.getColor(context, R.color.gray20));
            textView.getPaint().setStyle(Paint.Style.STROKE);
            textView.setGravity(Gravity.CENTER_VERTICAL);
            LayoutParams params$ = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT);
            LayoutHelper.setMargin(params$, 0, 8, 0, 0);

            params$.addRule(RelativeLayout.BELOW, tvTop.getId());
            params$.addRule(RelativeLayout.ALIGN_LEFT, tvTop.getId());
            addView(textView, params$);
            LayoutHelper.setMargin(params, 5, 0, 0, 0);
            params.addRule(RelativeLayout.RIGHT_OF, textView.getId());
        } else if(type == ContentType.TYPE_CHOOSE_PHOTO){

            editText.setVisibility(GONE);

            imgPhoto = new SimpleDraweeView(context);
            imgPhoto.setId(ViewHelp.generateViewId());
            imgPhoto.setActualImageResource(R.drawable.pic_first);

            imgPhoto.setOnClickListener(onClickListener);

            LayoutParams lp = LayoutHelper.createRelative(dip2Px(24), dip2Px(24));
            lp.addRule(RelativeLayout.BELOW, tvTop.getId());
            lp.addRule(RelativeLayout.ALIGN_LEFT, tvTop.getId());
            LayoutHelper.setMargin(lp, 0, 8, 0, 0);
            addView(imgPhoto, lp);
            LayoutHelper.setMargin(params, 5, 0, 0, 0);
            params.addRule(RelativeLayout.RIGHT_OF, imgPhoto.getId());
        } else  if(type == ContentType.TYPE_LABEL){
            editText.setFocusable(false);
            editText.setEnabled(false);
            editText.setClickable(false);
            editText.setFocusableInTouchMode(false);
          editText.setTextSize(14);
          editText.setBackground(null);

            editText.setTextColor(ContextCompat.getColor(context,R.color.textColorSecondary));

            params.width = LayoutHelper.WRAP_CONTENT;
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            params.addRule(RelativeLayout.BELOW,0);
            LayoutHelper.setMargin(params, 5, 0, 8, 0);
            //params.addRule(RelativeLayout.CENTER_VERTICAL);
            params.addRule(RelativeLayout.ALIGN_BASELINE,tvTop.getId());

        }else {
            editText.setFocusable(true);
            editText.setOnClickListener(null);
            params.addRule(RelativeLayout.ALIGN_LEFT, tvTop.getId());

        }
//        params.setMargins(params.leftMargin,0,params.rightMargin,0);
        addView(editText, params);


        if (showArrow12) {

            AppCompatImageView ivArrow = new AppCompatImageView(context);
            try {
                ivArrow.setImageDrawable(AppCompatResources.getDrawable(context,R.drawable.ic_arrow_drop_down_black_12dp));
            } catch (Throwable e) {
                e.printStackTrace();
            }

            LayoutParams innerParams = LayoutHelper.createRelative(14, 14);
            innerParams.addRule(ALIGN_PARENT_RIGHT);
            innerParams.addRule(RelativeLayout.CENTER_VERTICAL);
            innerParams.addRule(RelativeLayout.ALIGN_TOP,editText.getId());
            innerParams.addRule(RelativeLayout.ALIGN_BOTTOM,editText.getId());
            //LayoutHelper.setMargin(innerParams, 0, 0, 0, 0);
            addView(ivArrow, innerParams);
        }

//        if (!TextUtils.isEmpty(showHelp)) {
//            ImageView imageView = new ImageView(context);
//            imageView.setBackgroundResource(R.drawable.icon_help);
//            LayoutParams relative = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
//            relative.addRule(ALIGN_PARENT_RIGHT);
//            LayoutHelper.setMargin(relative, 0, 0, 20, 0);
//            addView(imageView, relative);
//        }
        if (showHelp != 0) {
            ImageView ivHelp = new ImageView(context);
            ivHelp.setImageResource(R.drawable.help);
            layoutParams = LayoutHelper.createRelative(14, 14);
            layoutParams.addRule(ALIGN_PARENT_RIGHT);
            layoutParams.addRule(RelativeLayout.ALIGN_TOP,editText.getId());
            layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM,editText.getId());

            //LayoutHelper.setMargin(layoutParams, 0, 10, 0, 0);
            addView(ivHelp, layoutParams);
            LayoutHelper.setSelectable(ivHelp);
            ivHelp.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showHelp();
                }
            });
        }

        tvTop.setText(topTip);
    }

    private void showHelp() {
        int showHelp = mTipMap.showHelp;
        if (showHelp == 0) return;
        Dialog builder = new Dialog(getContext(), R.style.Theme_AppCompat_Light_Dialog_Alert);
        builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
        builder.getWindow().setBackgroundDrawable(
                new ColorDrawable(android.graphics.Color.TRANSPARENT));
//        builder.setOnDismissListener(dialogInterface -> {
//            //nothing;
//        });
        builder.setCancelable(true);
        builder.setCanceledOnTouchOutside(true);
        RoundedImageView imageView = new RoundedImageView(getContext());
        imageView.setImageResource(showHelp);
        imageView.setCornerRadius(SizeUtils.dp2px(15f));
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        builder.addContentView(imageView, new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = builder.getWindow();
        WindowManager m = window.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        Point point = new Point();
        d.getSize(point);
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
//        p.height = (int) (d.getHeight()*0.48 ); // 高度设置为屏幕的0.6
        p.width = (int) (point.x * 0.8); // 宽度设置为屏幕的0.65
        p.height = (int) (point.y * 0.65);
        window.setAttributes(p);
        builder.show();

    }

    private void showAddressDialog() {

    }

    public void setOnItemClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
        if(imgPhoto != null){
            imgPhoto.setOnClickListener(onClickListener);
        }
    }

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private void showChooseDate() {
        Context context = getContext();
        Calendar calendar = Calendar.getInstance();



//        int year = Math.max(calendar.get(Calendar.YEAR), 2017);
//        int month = calendar.get(Calendar.MONTH);
//        int dayOfM = calendar.get(Calendar.DAY_OF_MONTH);
        int year = Math.max(calendar.get(Calendar.YEAR), 2017);
        int month = 0;
        int dayOfM = 1;

        if(chooseCalendar != null){
            year = chooseCalendar.get(Calendar.YEAR);
            month = chooseCalendar.get(Calendar.MONTH);
            dayOfM = chooseCalendar.get(Calendar.DAY_OF_MONTH);
        }


        DatePickerDialog datePickerDialog = DialogFactory.createDatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                if (chooseCalendar == null) {
                    chooseCalendar = Calendar.getInstance();
                }
                chooseCalendar.set(Calendar.YEAR, year);
                chooseCalendar.set(Calendar.MONTH, month);
                chooseCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                editText.setText(format.format(chooseCalendar.getTime()));
            }
        }, year, month, dayOfM);
        DatePicker datePicker = datePickerDialog.getDatePicker();
        datePicker.setMaxDate(calendar.getTimeInMillis());
        datePickerDialog.show();
    }

    private int dip2Px(float dip) {
        return (int) (dip * getContext().getResources().getDisplayMetrics().density + 0.5f);
    }


    public boolean isEmpty(){
        if(mTipMap.type == ContentType.TYPE_CHOOSE_PHOTO){
            return TextUtils.isEmpty(imgPath);
        }else {
            CharSequence text = editText.getText();
            return TextUtils.isEmpty(text);
        }

    }

    public String getContent() {
        if(mTipMap.type == ContentType.TYPE_CHOOSE_PHOTO){
            return imgPath;
        }else {
            CharSequence text = editText.getText();
            if (TextUtils.isEmpty(text)) {
                String concat = TextUtils.concat(mTipMap.topTip, "不能为空").toString();
                Toast.makeText(editText.getContext(), concat, Toast.LENGTH_SHORT).show();
//            throw new IllegalArgumentException(concat);
                return null;
            } else if (filter == null || filter.filter(text)) {
                return String.valueOf(text);
            } else {
                Toast.makeText(editText.getContext(), TextUtils.concat("请输入正确的", mTipMap.topTip),
                    Toast.LENGTH_SHORT).show();
                return null;
            }

        }
    }

    public void setContext(String str) {
        if(mTipMap.type == ContentType.TYPE_CHOOSE_PHOTO){
            imgPath = str;

            Uri uri = UriUtil.getUriForFile(new File(str));
            FrescoUtils.removeCache(uri);
            imgPhoto.setImageURI(uri);
        }else if (mTipMap.type == ContentType.TYPE_DATE){
            try {
                if (!TextUtils.isEmpty(str)){
                    Date parse = format.parse(str);
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(parse);
                    editText.setText(str);

                    chooseCalendar = instance;
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }else {
            editText.setText(str);
        }
    }

}
